<script setup lang="ts">
import { showNotify,Uploader } from 'vant' // 可选：根据你的UI库引入提示组件，如 Element-UI, Vant 等
import {ref} from "vue"
import { get,post } from '@/utils/service'
import { VUE_APP_BASE_API,SESSION_LAST_CODE } from '@/utils/baseConfig'
const modifyNameState = ref(false)
const showSexState = ref(false)
const loadingStatus = ref(false)
const moidfyType=ref(1)
const member=ref({});
const weixinAccount=ref({});
const name=ref("")
const nickName=ref("")
const paramsName=ref("")
const sex=ref("")
  const actions = [
    { name: '男' },
    { name: '女' },
  ];
const paramsTitle=ref("姓名");
const avatarImg = ref(VUE_APP_BASE_API+'/images/vue/myHeader.png')
function onClickLeft() {
  window.history.back()
}
function modifyName() {
  modifyNameState.value=true;
  paramsName.value=name.value;
  paramsTitle.value="姓名";
  moidfyType.value=1;
}
function modifyNickName() {
  modifyNameState.value=true;
  paramsName.value=nickName.value;
  paramsTitle.value="昵称";
  moidfyType.value=2;
}
function modifySex(){
  showSexState.value=true;
}
function nameValidator(){
  const length=paramsName.value.length;
  if(length<2||length>20){
    return "请输入正确的"+paramsTitle.value+"，"+paramsTitle.value+"长度2-20个字符"
  }
}
queryCarMasterWechat();
queryAccount();
function queryCarMasterWechat() {
  // 异步更新数据
  // setTimeout 仅做示例，真实场景中一般为 ajax 请求
  get('/memberWechatNew/queryCarMasterWechat', {})
    .then((res) => {
      if (res.code === 0) {
        const memberInfo=res.data.member;
        member.value = memberInfo
        name.value=memberInfo.name;
        nickName.value=memberInfo.nickName
        paramsName.value=memberInfo.name;
        sex.value=memberInfo.sex
        const tempAvatarUrl=memberInfo.avatarUrl;
        console.log(tempAvatarUrl)
        if (tempAvatarUrl != null && tempAvatarUrl != '') {
          if(tempAvatarUrl.indexOf("https")!=-1){
            avatarImg.value = memberInfo.avatarUrl
          }else{
            avatarImg.value = VUE_APP_BASE_API+memberInfo.avatarUrl
          }
        }
      } else {
        showNotify({ type: 'danger', message:'获取会员信息失败', color: '#FFF', background: '#797979' })
      }
    })
    .catch((err) => {
      console.log(err)
    })
}
function queryAccount(){
  const code = localStorage.getItem(SESSION_LAST_CODE) //获取微信code
  get('/weixinAccountWechatNew/queryWechatByCode', {code: code,})
    .then((res) => {
      console.log(res)
      if (res.code == 0) {
        weixinAccount.value = res.data
      }
    })
}

function saveModifySex(item:object){
   get('/memberWechatNew/saveWechatSex', {sex:item.name})
    .then((res) => {
      if(res.code==0){
      sex.value=item.name;
      showNotify({ type: 'success', message: res.msg , duration: 3000 })
    }else{
      showNotify({ type: 'danger', message: res.msg, color: '#FFF', background: '#797979' })
    }
  })
}
function onFailed(errorInfo: Error | string) {
  console.log('failed', errorInfo)
}
function saveModifyName(tempname:string){
   get('/memberWechatNew/saveWechatName', {name:tempname})
    .then((res) => {
      if(res.code==0){
      name.value=tempname;
      setTimeout(() => {
        modifyNameState.value=false;
      }, 1000);
      showNotify({ type: 'success', message: res.msg , duration: 3000 })
    }else{
      showNotify({ type: 'danger', message: res.msg, color: '#FFF', background: '#797979' })
    }
  })
}
function saveModifyNickName(tempNickName:string){
  get('/memberWechatNew/saveWechatNickName', {nickName:tempNickName})
  .then((res) => {
    if(res.code==0){
      nickName.value=tempNickName;
      showNotify({ type: 'success', message: res.msg , duration: 3000 })
      setTimeout(() => {
        modifyNameState.value=false;
      }, 1000);
    }else{
      showNotify({ type: 'danger', message: res.msg, color: '#FFF', background: '#797979' })
    }
  })
}
function submitFrm(value:object){
  loadingStatus.value = true // 显示加载状态
  try {
    const type=moidfyType.value;
    if(type==1){
      saveModifyName(value.name);
    }else
    if(type==2){
      saveModifyNickName(value.name);
    }else{
       showNotify({ type: 'danger', message:"保存失败，未知修改类型", color: '#FFF', background: '#797979' })
    }
  } catch (error) {
    console.log('submit error:' + error)
    loadingStatus.value = false // 隐藏加载状态
    showNotify({ type: 'danger', message: error, color: '#FFF', background: '#797979' })
  } finally {
    loadingStatus.value = false // 隐藏加载状态
  }
}
function chooseImage() {
  // 触发文件选择对话框
  Uploader.click();
}
function  afterRead(file:object) {
      // 这里处理上传逻辑，例如上传到服务器
    const formData = new FormData();
    formData.append('file', file.file);

    // 示例：使用 axios 上传图片
    post('/swfUpload/uploadFileLayui', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    }).then(res => {
      // 更新 imageURL 为上传后返回的新头像URL
      if(res.code==0){
        avatarImg.value =VUE_APP_BASE_API+ res.url; // 假设服务器返回新头像URL在data.url中
        saveAvatarImage(res.url)
      }else{
        showNotify({ type: 'danger', message: '图片更新失败', color: '#FFF', background: '#797979' })
      }
    }).catch(error => {
      console.error('上传失败:', error);
    });
  }
  function saveAvatarImage(avatarImg:string){
    get('/memberWechatNew/saveWechatAvatarImage', {avatarImg:avatarImg})
  .then((res) => {
    if(res.code==0){
      showNotify({ type: 'success', message: res.msg , duration: 3000 })
      setTimeout(() => {
        modifyNameState.value=false;
      }, 1000);
    }else{
      showNotify({ type: 'danger', message: res.msg, color: '#FFF', background: '#797979' })
    }
  })
  }
</script>
<template>
  <van-nav-bar title="车主信息" left-text="返回" left-arrow @click-left="onClickLeft" />
  <div class="mainContent">
    <van-cell-group inset>
      <van-cell v-if="weixinAccount.dbid!=undefined" title="公众号" :value="weixinAccount.name" size="large"  />
      <van-cell title="门店" :value="member.wechatRegEnterpriseName" size="large"  />
      <van-cell title="头像" size="large" is-link >
        <template #right-icon>
          <van-uploader :after-read="afterRead" :deletable="false">
            <img :src="avatarImg" alt="头像" style="width: 30px; height: 30px; border-radius: 50%;margin-right: 12px;" @click="chooseImage">
          </van-uploader>
      </template>
      </van-cell>
      <van-cell title="姓名" :value="name" size="large" is-link @click="modifyName" />
      <van-cell title="性别" :value="sex" size="large" is-link @click="modifySex"/>
      <van-cell title="昵称" :value="nickName" size="large" is-link @click="modifyNickName"/>
    </van-cell-group>
  </div>
  <br />
  <br />
  <br />
   <van-popup
    closeable
    v-model:show="modifyNameState"
    position="bottom"
    round
    :style="{ height: '40%' }"
  >
    <div>
      <h3 class="memberInfoPopTitle">修改{{ paramsTitle }}</h3>
    </div>
    <div class="memberInfoPopContainer">
            <van-form @failed="onFailed" @submit="submitFrm">
            <br></br>
            <br></br>
            <van-cell-group inset>
              <van-field
                v-model="paramsName"
                :label="paramsTitle"
                required="true"
                name="name"
                :placeholder="paramsTitle"
                type="text"
                :rules="[
                  { required: true, message: '请填'+paramsTitle },
                  {
                    validator: nameValidator,
                    message: '请输入'+paramsTitle,
                    trigger: 'onChange',
                  },
                ]"
              />
            </van-cell-group>
               <br />
            <div class="memberInfoPopButton">
              <van-button
                round
                block
                type="primary"
                :loading="loadingStatus"
                loading-type="spinner"
                loading-text="提交中..."
                native-type="submit"
              >
              保存
            </van-button>
            </div>
            </van-form>
      </div>
  </van-popup>
     <van-action-sheet
      v-model:show="showSexState"
      :actions="actions"
      cancel-text="取消"
      description="选择性别"
      @select="saveModifySex"
      close-on-click-action
    />
</template>

<style>
.van-icon__image {
  display: block;
  width: 1.5em;
  height: 1.5em;
  object-fit: contain;
}
.clearButton {
  background-color: #d7d7d7;
  color: #797979;
  width: 100%;
}
</style>
